package com.wasion.gydpe.service.impl;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import CommProxy.DataFrame;
import CommProxy.IWriteablePrx;
import CommProxy.IWriteablePrxHelper;
import CommProxy.InstructionFrame;

import com.wasion.gydpe.common.util.ConfigReader;
import com.wasion.gydpe.common.util.ConvertInXBaseUtil;
import com.wasion.gydpe.common.util.PnFn;
import com.wasion.gydpe.ice.TestProperties;
import com.wasion.gydpe.service.ZoneAreaMonitorService;

/**
 * 
 * @ClassName: ZoneAreaMonitorServiceImpl
 * @Description: 台区监控模块的业务层接口实现ServiceImpl
 * @author 高意
 * @date Aug 28, 2012 3:05:49 PM
 * 
 */
@Service
public class ZoneAreaMonitorServiceImpl implements ZoneAreaMonitorService {

	// 日志
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ZoneAreaMonitorServiceImpl.class);

	// 获取折现图的宽度和高度
	static ConfigReader configReader = null;
	static {
		try {
			configReader = new ConfigReader("config/system.properties");
		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.error("读取配置文件失败: ZoneAreaMonitorServiceImpl====" + e);
		}
	}

	// 从ICE的配置文件中读取前端机的信息
	static TestProperties ec = TestProperties.getInstance();
	private static final String COMMUNICATION_SENDER = ec.getPropertyValue(
			"/IceComm.properties", "Communication.sender");
	private static final String SERVERPROXY_SERVER = ec.getPropertyValue(
			"/IceComm.properties", "ServerProxy.server");

	// 信息点号，即测量点号
	private static final int N = Integer.parseInt(configReader
			.getProperty("measuringPoint.terminal"));

	// 应用功能标识
	private static final short AFN = 0x0D;

	/**
	 * 查看有功功率曲线
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void showActivePowerCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(81),
				PnFn.getPn(N) + PnFn.getFn(82), PnFn.getPn(N) + PnFn.getFn(83),
				PnFn.getPn(N) + PnFn.getFn(84) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看无功功率曲线
	 */
	@SuppressWarnings("unchecked")
	public void showReactivePowerCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(85),
				PnFn.getPn(N) + PnFn.getFn(86), PnFn.getPn(N) + PnFn.getFn(87),
				PnFn.getPn(N) + PnFn.getFn(88) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看功率因数曲线
	 */
	@SuppressWarnings("unchecked")
	public void showPowerFactorCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(105),
				PnFn.getPn(N) + PnFn.getFn(106),
				PnFn.getPn(N) + PnFn.getFn(107),
				PnFn.getPn(N) + PnFn.getFn(108) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看电压曲线
	 */
	@SuppressWarnings("unchecked")
	public void showVoltageCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(89),
				PnFn.getPn(N) + PnFn.getFn(90), PnFn.getPn(N) + PnFn.getFn(91) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}

	}

	/**
	 * 查看电流曲线
	 */
	@SuppressWarnings("unchecked")
	public void showCurrentCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(92),
				PnFn.getPn(N) + PnFn.getFn(93), PnFn.getPn(N) + PnFn.getFn(94) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看零序电流曲线
	 */
	@SuppressWarnings("unchecked")
	public void showZeroSequenceCurrentCurve(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(95) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看有功总电能量曲线
	 */
	@SuppressWarnings("unchecked")
	public void showActivePowerEnergy(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(97),
				PnFn.getPn(N) + PnFn.getFn(99) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看无功总电能量曲线
	 */
	@SuppressWarnings("unchecked")
	public void showReactivePowerEnergy(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(98),
				PnFn.getPn(N) + PnFn.getFn(100) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看有功总电能示数曲线
	 */
	@SuppressWarnings("unchecked")
	public void showActivePowerIndication(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(101),
				PnFn.getPn(N) + PnFn.getFn(103) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 查看无功总电能示数曲线
	 */
	@SuppressWarnings("unchecked")
	public void showReactivePowerIndication(Map paramsMap) {

		String terminalAddr = (String) paramsMap.get("terminalAddr");

		String[] dataUnitIndetify = { PnFn.getPn(N) + PnFn.getFn(102),
				PnFn.getPn(N) + PnFn.getFn(104) };

		String dataUnit = getStartTime() + "01" + "60";

		for (int i = 0; i < dataUnitIndetify.length; i++) {
			this
					.aFNODHRequest(terminalAddr, AFN, dataUnitIndetify[i],
							dataUnit);
		}
	}

	/**
	 * 请求2类数据
	 */
	protected int aFNODHRequest(String terminalAddr, short afn,
			String dataUnitIndetify, String dataUnit) {

		int returnNum = -1;
		try {
			// 指令帧继承自CBasicParameter，包含1.sender、receiver、seqID、isWait、isResponse属性
			// 2.数据帧结构DataFrame(iertuAddr 集中器地址
			// subErtuAddr 从集中器地址（如果不是级联集中器，两个地址一样）
			// AFN Afn commMode 集中器上行通讯方式 0:tcp 1:udp 2:拨号
			// tele 电话号码 protocol 规约 option 附加标志 ：100表示不带时标 DataPart data 数据体)
			InstructionFrame frame2 = new InstructionFrame();
			frame2.sender = COMMUNICATION_SENDER;
			frame2.isWait = true;
			frame2.isResponse = true;

			// 转换终端地址
			String terminalAddrExch = terminalAddr.substring(4)
					+ terminalAddr.substring(0, 4);
			int terminalAddrInt = BigInteger.valueOf(
					Long.valueOf(terminalAddrExch, 16)).intValue();

			byte[] hexBytes = ConvertInXBaseUtil
					.hexString2ByteArray(dataUnitIndetify + dataUnit);

			frame2.frame = new DataFrame();
			frame2.frame.protocol = 0x28; // 规约
			frame2.frame.commMode = 0; // 集中器上行通讯方式 0:tcp 1:udp 2:拨号
			frame2.frame.tele = ""; // 电话号码
			frame2.frame.afn = afn;
			frame2.frame.ertuAddr = terminalAddrInt;
			frame2.frame.subErtuAddr = terminalAddrInt;
			frame2.frame.data = hexBytes;

			// ICE下行
			Ice.Communicator ic = null;
			ic = Ice.Util.initialize();
			Ice.ObjectPrx base = ic.stringToProxy(SERVERPROXY_SERVER);

			if (base == null) {
				throw new RuntimeException("Cannot create proxy");
			}

			IWriteablePrx rootDir = IWriteablePrxHelper.checkedCast(base);
			if (rootDir == null) {
				throw new RuntimeException("Invalid proxy");
			}

			returnNum = rootDir.trans(frame2);
		} catch (NullPointerException e) {
			e.printStackTrace();
			LOGGER.error("空指针异常：aFNODHRequest====" + e);
		}
		return returnNum;
	}

	/**
	 * 获取起始时间，格式化，形式如:3011150812，表示：2012-08-15 11:30:00
	 */
	protected String getStartTime() {

		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		// 时间为前一天到现在
		int day = calendar.get(Calendar.DAY_OF_MONTH) - 1;
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minuter = calendar.get(Calendar.MINUTE);
		String startTime = ((minuter + "").length() < 2 ? "0" + minuter
				: (minuter + ""))
				+ ((hour + "").length() < 2 ? "0" + hour : (hour + ""))
				+ ((day + "").length() < 2 ? "0" + day : (day + ""))
				+ ((month + "").length() < 2 ? "0" + month : (month + ""))
				+ (year + "").substring(2);

		return startTime;
	}

}
